package com.yunpuvip.sachet.rest.controller.port;

import cn.hutool.json.JSONUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.yunpuvip.sachet.biz.entity.Player;
import com.yunpuvip.sachet.biz.service.PlayerService;
import com.yunpuvip.sachet.biz.service.SysparamService;
import com.yunpuvip.sachet.modular.constant.response.ServerResponse;
import com.yunpuvip.sachet.modular.core.exception.RestServiceExceptionEnum;
import com.yunpuvip.sachet.modular.util.cache.CacheKit;
import com.yunpuvip.sachet.modular.util.sms.Sendsms;
import com.yunpuvip.sachet.rest.common.util.VerifyCodeKit;
import com.yunpuvip.sachet.rest.common.WxTool;
import com.yunpuvip.sachet.rest.common.vo.AuthResponse;
import com.yunpuvip.sachet.rest.common.vo.LoginVo;
import com.yunpuvip.sachet.rest.common.vo.PlayerVo;
import com.yunpuvip.sachet.rest.common.vo.WeChatUser;
import com.yunpuvip.sachet.rest.controller.common.RestBaseController;
import com.yunpuvip.sachet.rest.modular.auth.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;

/**
 * @ auther wushaohong
 * @ date  2019/8/10
 **/
@RequestMapping("login")
@RestController
@Slf4j

public class LoginController extends RestBaseController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SysparamService sysparamService;

    @Autowired
    PlayerService playerService;

    @Autowired
    private WxTool wxTool;


    /**
     * 公众号 授权获取( getCode )
     *
     * @return void
     * @author hyf
     * @date 2019-03-11
     */
    @RequestMapping("/openid")
    public void redirectToGetOpenidForce(HttpServletResponse response, String userNo, String qrcode) throws IOException {
        String host = sysparamService.loadSetting("webhost").getParamValue();
        String appid = sysparamService.loadSetting("AppID").getParamValue();
        String appName = sysparamService.loadSetting("appName").getParamValue();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(host).append("/").append(appName).append("/player/getOpenid?");
        // 默认都会传
        stringBuilder.append("params=").append(qrcode).append("--").append(userNo);
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + stringBuilder.toString() + "&response_type=code&scope=snsapi_userinfo#wechat_redirect";
        System.out.println("待跳转的完整URL：" + url);
        response.sendRedirect(url);
    }
















    /**
     * 公众号  获取授权用户信息
     * 用code换取oauth2的openid
     * 详情请见: http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html
     * 这代码。。醉了
     * @param code code
     */
    @RequestMapping(value = "/getOpenid")
    public Object getOpenid(HttpServletResponse response
            , @RequestParam(value = "code") String code
            , String redirectUrll
            , @RequestParam(value = "params") String params) throws IOException {
        log.info("开始通过code 获取openid以及用户信息");
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxTool.getWxMpOAuth2AccessToken(code);
        WeChatUser weChatUser = wxTool.getWeChatUserInfo(wxMpOAuth2AccessToken.getAccessToken(), wxMpOAuth2AccessToken.getOpenId());
        String qrcode = "";
        String userno = "";
        System.out.println("取到了params:" + params);
        if (StringUtils.isNotBlank(params)) {
            String[] ps = params.split("--");
            if (ps.length == 2) {
                qrcode = ps[0];
                userno = ps[1];
            }
        }
        if (StringUtils.isNotBlank(userno) && !"undefined".equals(userno)) {
            weChatUser.setUserNo(userno);
        }
        if (StringUtils.isNotBlank(qrcode) && !"undefined".equals(qrcode)) {
            weChatUser.setQrcode(qrcode);
        }
        System.out.println("获取到的用户信息：" + weChatUser);
        log.info("用户信息获取成功");
        // 登录 获取用户信息
        PlayerVo playerVo = null;
        StringBuilder builder = new StringBuilder();
        System.out.println(builder);
        return JSONUtil.toJsonPrettyStr(weChatUser);
       /* try {
            playerVo = playerService.playerLogin(weChatUser, WeChatLoginType.WECHAT_PUBLIC_ACCOUNT.getCode());
        } catch (RestException e) {
            e.printStackTrace();
            // 注册失败
            log.error("用户登录或注册失败。", e);
            String url = sysparamService.loadSetting("errorJumpUrl").getParamValue();
            builder.append(url).append("?code=").append(e.getCode()).append("&msg=").append(e.getMessage());
            System.out.println("RestException异常：准备跳转的完整url=" + builder.toString().trim());
            response.sendRedirect(builder.toString().trim());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("为什么是Exception错误。", e);
            String url = sysparamService.loadSetting("errorJumpUrl").getParamValue();
            builder.append(url).append("?code=").append(500).append("&msg=").append(e.getMessage());
            System.out.println("Exception异常：准备跳转的完整url=" + builder.toString().trim());
            response.sendRedirect(builder.toString().trim());
        }
        // 组装跳转信息
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(playerVo.getId() + "", randomKey);

        if (StringUtils.isBlank(redirectUrll)) {
            String url = sysparamService.loadSetting("frontEndJumpUrl").getParamValue();
            builder.append(url).append("?token=").append(token);
        } else {
            builder.append(redirectUrll).append("?token=").append(token);
        }
        builder.append("&code=200");
        System.out.println("准备跳转的完整url=" + builder.toString().trim());
        response.sendRedirect(builder.toString().trim());*/
    }






    /**
     *获取用户的基本信息
     * @param playerVo
     * @return
     */
    private ResponseData getLoginResponseData(PlayerVo playerVo) {
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(playerVo.getId() + "", randomKey);
        playerVo.setId(null);
        playerVo.setAgentId(0);
        playerVo.setIntroducerId(0);
        return ResponseData.success(new AuthResponse(token, randomKey, playerVo));
    }

    /**
     *
     * 短信验证登录
     * @param loginVo
     *
     * @return
     */
    @RequestMapping(value = "/auth")
    public ServerResponse playerLogin(@Valid LoginVo loginVo ){
        String openid = loginVo.getOpenid();
        String phoneNumber = loginVo.getPhoneNumber();
        //检查验证码
        boolean res = false;
        res=VerifyCodeKit.checkVerifyCode(loginVo.getPhoneNumber(), loginVo.getVerifyCode());
        if(!res){
            return ServerResponse.creatByErrorEnum(RestServiceExceptionEnum.PHONE_CODE_NOT_MISMATCH);
        }
        //查看用户是否已注册

        //查看号码是否已被绑定


        //将登录的用户信息缓存
        //生成token
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(loginVo.getPhoneNumber(), randomKey);
        HashMap<String, Object> map = new HashMap<>();
        map.put("atuhInfo",new AuthResponse(token, randomKey));
        return  ServerResponse.creatBySuccess(dataMap("info",map));
    }

    /**
     * 发送用户验证码
     * @param phoneNumber
     *     REGISTER(1, "注册"),
     *     UPDATEPASSWORD(2, "修改密码"),
     *     VALIDNO(3, "通用验证码");
     * @return
     */

    @RequestMapping(value = "/verifyCode")
    public ServerResponse getVerifyCode(@RequestParam String phoneNumber, @RequestParam(required = false,defaultValue = "1")  Integer sendType){
        //获取短信验证码
        String code = Sendsms.sendSmsCodeCommon(phoneNumber, sendType);
        HashMap<String,String> map = new HashMap<>();
        //缓存验证码
        VerifyCodeKit.putVerifyCode(phoneNumber,code);
        return ServerResponse.creatBySuccessMessage("短信验证码发送成功");
    }

    @RequestMapping("test")
    public String testCache(String test ) {
        String o = (String)CacheKit.get("test", "hello");
        return o;
    }


    @RequestMapping("testTwo")
    public String testTwo( ) {

         CacheKit.put("test","hello","123456");
            return  "ok";
    }

}
